package handlers

import (
	"ai/internal/response"
	"net/http"
	"strings"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// AuthMiddleware checks the JWT token
func AuthMiddleware(c *gin.Context) {
	authHeader := c.GetHeader("Authorization")
	if authHeader == "" {
		response.ResponseWithCode(c, "unauthorized", "Authorization header is required", nil)
		c.Abort()
		return
	}

	tokenString := strings.TrimPrefix(authHeader, "Bearer ")
	if tokenString == authHeader {
		response.Error(c, http.StatusUnauthorized, "Bearer token is required")
		c.Abort()
		return
	}

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Validate the signing method
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, jwt.ErrSignatureInvalid
		}
		return []byte("your_secret_key"), nil
	})

	if err != nil || !token.Valid {
		response.ResponseWithCode(c, "unauthorized", "Invalid token", nil)
		c.Abort()
		return
	}

	// Token is valid, proceed with the request
	c.Next()
}

// CorsMiddleware handles CORS
func CorsMiddleware(c *gin.Context) {
	c.Header("Access-Control-Allow-Origin", "*")
	c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
	c.Header("Access-Control-Allow-Headers", "Content-Type, Authorization")
	c.Next()
}
